<template>
  <div v-if="isReload">
    <card :isCustomHeader="true">
      <template #header>
        <t-breadcrumb :maxItemWidth="'150'">
          <t-breadcrumbItem>企业管理</t-breadcrumbItem>
          <t-breadcrumbItem><b>角色</b></t-breadcrumbItem>
        </t-breadcrumb>
        <t-button @click="$router.push('/business-management/role/addRole')">添加角色</t-button>
      </template>
      <template>
        <t-space direction="vertical" style="width: 100%">
          <t-row>
            <t-col :span="2">
              <div class="box">
                <t-space :size="8">
                  <t-button
                    @click="handleDeleteRow"
                    variant="outline"
                    theme="danger"
                    :disabled="selectedRowKeys.length === 0"
                    >批量删除</t-button
                  >
                </t-space>
              </div>
            </t-col>
            <t-col :span="2" :offset="8">
              <t-input autofocus style="width: 90%" clearable @change="search">
                <search-icon slot="prefix-icon"></search-icon>
              </t-input>
            </t-col>
          </t-row>
        </t-space>
        <t-table
          rowKey="id"
          :data="data"
          :columns="columns"
          :sort="sort"
          @sort-change="sortChange"
          :showSortColumnBgColor="true"
          :filter-value="filterValue"
          @filter-change="onFilterChange"
          :hover="hover"
          :size="size"
          :table-layout="tableLayout ? 'auto' : 'fixed'"
          :showHeader="showHeader"
          :filterRow="() => null"
          @select-change="rehandleSelectChange"
          cellEmptyContent="-"
        >
        </t-table>
        <t-pagination
          v-model="pagination.defaultCurrent"
          @change="pageChange"
          :total="pagination.total"
          :page-size.sync="pagination.defaultPageSize"
          show-jumper
          class="pagination"
        />
      </template>
    </card>
  </div>
</template>

<script lang="jsx">
import { mapState } from 'vuex';
import Card from '@/components/Card/index.vue';
import { SearchIcon, DeleteIcon, EditIcon, EllipsisIcon } from 'tdesign-icons-vue';
import { DialogPlugin } from 'tdesign-vue';
import { deleteRole } from '@/service/business-management/role/index';
import { debounce } from '@/utils';

export default {
  name: 'BusinessManagementRole',
  components: {
    Card,
    SearchIcon,
  },
  data() {
    return {
      isReload: true,
      // 选中行
      selectedRowKeys: [],
      total: 0,
      data: [],
      filterValue: {
        createTime: [],
      },
      // 操作的关键词 筛选，排序
      oprationkW: {},
      size: 'medium',
      tableLayout: false,
      hover: true,
      showHeader: true,
      // 排序
      sort: {
        // 按照 status 字段进行排序
        sortBy: 'ID',
        // 是否按照降序进行排序
        descending: false,
      },
      columns: [
        {
          colKey: 'row-select',
          type: 'multiple',
          className: 'demo-multiple-select-cell',
        },
        // 过滤
        {
          colKey: 'roleName',
          title: '角色名称',
          sorter: true,
          ellipsis: true,
          ellipsisTitle: false,
          // 多选过滤配置
          filter: {
            type: 'multiple',
            showConfirmAndReset: true,
            list: [],
          },
        },
        {
          colKey: 'belongOrg',
          title: '所属企业',
          ellipsis: true,
        },
        {
          colKey: 'createName',
          title: '创建人',
          ellipsis: true,
          ellipsisTitle: false,
          sortType: 'all',
          sorter: true,
          // 多选过滤配置
          filter: {
            type: 'multiple',
            showConfirmAndReset: true,
            list: [],
          },
        },
        {
          colKey: 'description',
          title: '描述',
          ellipsis: true,
        },
        {
          colKey: 'action',
          title: '操作',
          width: 200,
          // 增、删、改、查 等操作
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          cell: (h, { row }) => (
            <div class="tdesign-table-demo__table-operations">
              <t-button variant="text" onClick={() => this.edit(row)}>
                <EditIcon></EditIcon>
              </t-button>
              <t-button variant="text" onClick={() => this.deleteRow(row)}>
                <DeleteIcon></DeleteIcon>
              </t-button>
              <t-button variant="text" onClick={() => this.ellipsis(row)}>
                <EllipsisIcon></EllipsisIcon>
              </t-button>
            </div>
          ),
        },
      ],
      // 分页器
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        total: 10,
      },
    };
  },
  computed: {
    ...mapState('businessRole', ['roleInfo']),
    ...mapState('user', ['userInfo']),
  },
  mounted() {
    this.getRoleInfo();
  },
  methods: {
    reload() {
      this.isReload = false;
      this.$nextTick(() => {
        this.isReload = true;
      });
    },
    async getRoleInfo() {
      const pageSize = this.pagination.defaultPageSize;
      const pageNum = this.pagination.defaultCurrent;
      const roleDTO = { pageNum, pageSize, ...this.oprationkW };

      await this.$store.dispatch('businessRole/requireAllRoleInfo', roleDTO);
      this.data = [];
      this.data = this.roleInfo?.allRolePage?.list;
      this.pagination.total = this.roleInfo.allRolePage.total;

      // 渲染筛选框选项内容
      this.columns[1].filter.list = this.roleInfo.roleSet;
      this.columns[3].filter.list = this.roleInfo.createSet;
    },
    // 输入框搜索
    search: debounce(function fn(value) {
      const inputContent = value;
      this.oprationkW = { ...this.oprationkW, inputContent };

      // 如果没有搜索参数value，接口要求也不传key
      if (!value) this.$delete(this.oprationkW, 'value');
      this.pagination.defaultCurrent = 1;
      this.getRoleInfo();
    }, 1000),
    // 排序
    sortChange(sort) {
      this.sort = sort;
      this.sortRequest(sort);
    },
    sortRequest(sort) {
      // 不排序的时候 不传参数
      if (!sort) {
        this.$delete(this.oprationkW, 'orderColum');
        this.$delete(this.oprationkW, 'orderType');
        this.getRoleInfo();
        return;
      }

      let orderColum;
      let orderType;
      orderType = 'desc';
      if (sort?.descending) orderType = 'asc';
      orderColum = 'createName';
      if (sort?.sortBy === 'roleName') orderColum = 'roleName';

      // 如果过滤也同时存在
      if (this.oprationkW.roleNameList) {
        this.oprationkW = { ...this.oprationkW, orderColum, orderType };
        this.getRoleInfo();
        return;
      }

      // 只有排序的时候
      this.oprationkW = { ...this.oprationkW, orderColum, orderType };
      this.getRoleInfo();
    },
    // 过滤
    onFilterChange(filters) {
      this.filterValue = {
        ...filters,
        createTime: filters.createTime || [],
      };
      this.filterRequest(this.filterValue);
    },
    filterRequest(filters) {
      const roleNameList = filters.roleName;
      const createNameList = filters.createName;
      this.oprationkW = { ...this.oprationkW, roleNameList, createNameList };

      // 如果没有过滤参数value，接口要求也不传key
      if (roleNameList?.length === 0) this.$delete(this.oprationkW, 'roleNameList');
      if (createNameList?.length === 0) this.$delete(this.oprationkW, 'createNameList');
      this.pagination.defaultCurrent = 1;
      this.getRoleInfo();
    },
    // 分页跳转
    pageChange({ current, pageSize }) {
      this.pagination.defaultCurrent = current;
      this.pagination.defaultPageSize = pageSize;
      this.getRoleInfo(current, pageSize);
    },
    // 选中行
    rehandleSelectChange(val) {
      this.selectedRowKeys = val;
    },
    // 删除
    handleDeleteRow() {
      this.deleteData(this.selectedRowKeys);
    },
    deleteRow(row) {
      this.deleteData([row.id]);
    },
    deleteData(ids) {
      const dialog = DialogPlugin.confirm({
        theme: 'warning',
        header: '提示',
        body: '再次确认是否删除？',
        onConfirm: () => {
          if (ids.includes(this.userInfo.roleId)) {
            this.$message.warning('不能删除自己的角色');
            return;
          }
          deleteRole(ids).then((res) => {
            if (!res || res.isError) return;
            this.$message.success('删除成功');
            this.selectedRowKeys = [];
            this.reload();
            this.getRoleInfo();
            dialog.destroy();
          });
        },
      });
    },
    edit(row) {
      this.$router.push({
        name: 'editRole',
        query: { id: row.id },
      });
    },
    ellipsis() {
      this.$message.info('该功能未开发，敬请期待');
    },
  },
};
</script>
<style lang="less" scoped>
.pagination {
  margin-top: 18px;
}
</style>
